package com.yami.shop.api.controller;

import com.yami.shop.api.config.HttpClient;
import com.yami.shop.api.config.ParamBuilder;
import com.yami.shop.api.config.SignHelper;
import com.yami.shop.bean.meituan.*;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.UserAddr;
import com.yami.shop.bean.model.UserAddrOrder;
import com.yami.shop.common.util.DateUtil;
import com.yami.shop.common.util.Json;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserAddrOrderService;
import com.yami.shop.service.UserAddrService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class CheckOrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserAddrService userAddrService;

    @Autowired
    private UserAddrOrderService userAddrOrderService;

    @PostMapping("/CheckOrder")
    public  void CheckOrder(String orderNumber) throws Exception {
        String appkey = OpenApiConfig.FORMAL_APP_KEY;
        String secret = OpenApiConfig.FORMAL_SECRET;
        String res=null;
        Order order = orderService.getOrderByOrderNumber(orderNumber);
        CheckRequest request = buildMockRequest(appkey,order);

        Map<String, String> params = ParamBuilder.convertToMap(request);
        String sign = SignHelper.generateSign(params, secret);

        params.put("sign", sign);

        try {
             res = HttpClient.post(RequestConstant.ORDER_CHECK_DELIVERY_ABILITY, params);
            CheckOrderResponse response = Json.parseObject(res, CheckOrderResponse.class);
            System.out.println("输出返回结果为"+response.toString());
        } catch (Exception e) {
            throw e;
        }
    }

    private  CheckRequest buildMockRequest(String appkey, Order order) {
        CheckRequest request = new CheckRequest();
        request.setAppkey(appkey);
        request.setTimestamp(com.yami.shop.common.util.DateUtil.unixTime());
        request.setVersion("1.0");
        /**
         * 设置配送服务编码
         *
         * 光速达:4001
         * 快速达:4011
         * 及时达:4012
         * 集中送:4013
         * 当天达:4021
         */
        request.setDeliveryServiceCode(4011);
        // 设置测试门店 id，测试门店的坐标地址为 97235456,31065079（高德坐标），配送范围3km
        request.setShopId(String.valueOf(order.getShopId()));
        // 收件人地址，最长不超过 512 个字符
        Long addorderId = order.getAddrOrderId();
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(addorderId);
        StringBuffer stringBuffer =null;
        double latResult=0.0;
        double lngResult = 0.0;
        if(userAddrOrder!=null){
            Long AddrId = userAddrOrder.getAddrId();
            UserAddr userAddr = userAddrService.getById(AddrId);
            if(userAddr!=null) {
                stringBuffer = new StringBuffer(userAddr.getProvince());
                stringBuffer.append(userAddr.getCity()).append(userAddr.getArea()).append(userAddr.getStreet()).append(userAddr.getAddr());
                //收件人经度（高德坐标），高德坐标 *（ 10 的六次方），如 116398419
                double cf = Math.pow(10,6);
                if(userAddr.getLat()!=null) {
                    double lat = Double.valueOf(userAddr.getLat());
                    latResult = lat*cf;
                    double lng = Double.valueOf(userAddr.getLng());
                    lngResult = lng*cf;
                }
                request.setReceiverLng(Integer.valueOf(new Double(lngResult).intValue()));
                //收件人纬度（高德坐标），高德坐标 *（ 10 的六次方），如 39985005
                request.setReceiverLat(Integer.valueOf(new Double(latResult).intValue()));
            }
        }
        request.setReceiverAddress(stringBuffer.toString());
        //预留字段，方便以后扩充校验规则，check_type = 1
        request.setCheckType(1);
        //模拟发单时间，时区为 GMT+8，当前距离 Epoch（1970年1月1日) 以秒计算的时间，即 unix-timestamp。
        request.setMockOrderTime(Long.valueOf(DateUtil.unixTime()));

        return request;
    }

    @PostMapping("/getShopArea")
    public  void getShopArea() throws Exception {
        String appkey = OpenApiConfig.FORMAL_APP_KEY;
        String secret = OpenApiConfig.FORMAL_SECRET;
        String res=null;
        QueryShopAreaRequest request = buildMockRequest(appkey);

        Map<String, String> params = ParamBuilder.convertToMap(request);
        String sign = SignHelper.generateSign(params, secret);

        params.put("sign", sign);

        try {
            res = HttpClient.post(RequestConstant.QUERY_SHOP_AREA, params);
            CheckOrderResponse response = Json.parseObject(res, CheckOrderResponse.class);
        } catch (Exception e) {
            throw e;
        }
    }

    private  QueryShopAreaRequest buildMockRequest(String appkey) {
        QueryShopAreaRequest request = new QueryShopAreaRequest();
        request.setAppkey(appkey);
        request.setTimestamp(com.yami.shop.common.util.DateUtil.unixTime());
        request.setVersion("1.0");
        /**
         * 设置配送服务编码
         *
         * 光速达:4001
         * 快速达:4011
         * 及时达:4012
         * 集中送:4013
         * 当天达:4021
         */
        request.setShopId("124");
        request.setDeliveryServiceCode(4011);
        return request;
    }



}
